package com.gec.news.controller;

import com.gec.news.entity.Users;
import com.gec.news.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 用户模块的控制器 接受用户的请求 并且进行处理
 */

@Controller
@RequestMapping("/users") //返回需要请求的页面
public class UsersContrller {
    @Autowired
    UserService userService;

    @Autowired
    HttpServletResponse response;

    @RequestMapping("/login")
    public String login(String userName, String password, HttpSession session) {
        //拿用户传过来的账号密码去数据库中比较
        Users user = userService.login(userName, password);
        if (user != null) {
            //有返回用户信息 账号密码正确 登录成功
            //将用户信息存放到session中
            session.setAttribute("loginUser", user);
            System.out.println("登录成功");
            //移除账号密码输入错误的信息
            session.removeAttribute("message");
//            try {
//                PrintWriter writer = response.getWriter();
//                writer.println("<script>alert('登录成功！')</script>");
//                Thread.sleep(1000);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
        } else {
//            try {
//                PrintWriter writer = response.getWriter();
//                writer.println("<script>alert('登录失败！')</script>");
//                Thread.sleep(1000);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            session.setAttribute("message","账号密码错误");
        }
        //返回首页从定向回首页
        return "redirect:/index.html";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/index.html";
    }
}
